package com.yingpai.fitness.dvp_2_0.main.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ViewGroup;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.orhanobut.logger.Logger;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.NoScrollViewPager;
import com.yingpai.fitness.dvp_2_0.main.fragment.home.DynamicFragment;
import com.yingpai.fitness.dvp_2_0.main.fragment.home.FitnessFragment;
import com.yingpai.fitness.dvp_2_0.main.fragment.home.MineFragment;
import com.yingpai.fitness.dvp_2_0.main.fragment.home.ShopFragment;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.entity.TabEntity;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by ASUS on 2018/11/2.
 */

public class HomeActivity extends CommonActivity implements Handler.Callback {

    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;
    @BindView(R.id.common_bottom_tab)
    CommonTabLayout commonBottomTab;
    private long exitTime;
    private ArrayList<Fragment> mFragments = new ArrayList<>();//存放Fragment

    private String[] mTitles = new String[4];
    //未选中图标
    private int[] mIconUnselectIds = new int[4];
    //选中后的图标
    private int[] mIconSelectIds = new int[4];

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private Messenger messenger;

    private Messenger mGetReplyMessenger = new Messenger(new Handler(this));

    private Handler delayHandler;

    //循环取当前时刻的步数中间的间隔时间
    private long TIME_INTERVAL = 500;
    private Intent intent;

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            try {
                messenger = new Messenger(service);
                Message msg = Message.obtain(null, Constant.NUM_0);
                msg.replyTo = mGetReplyMessenger;
                messenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.VIEWPAGER_FRAGMENT_STATUS);
        setContentView(R.layout.activity_home);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if(null != viewpager){
            viewpager.setCurrentItem(0);
        }
    }

    @Override
    protected void initView() {
        mTitles[0] = "商城";
        mIconSelectIds[0] = R.mipmap.icon_maintab_home_press;
        mIconUnselectIds[0] = R.mipmap.icon_maintab_home_normal;
        ShopFragment sportFragment = ShopFragment.newInstance();
        mFragments.add(sportFragment);

        mTitles[1] = "健身";
        mIconSelectIds[1] = R.mipmap.icon_maintab_shop_press;
        mIconUnselectIds[1] = R.mipmap.icon_maintab_shop_normal;
        FitnessFragment fitnessFragment = FitnessFragment.newInstance();
        mFragments.add(fitnessFragment);

        mTitles[2] = "动态";
        mIconSelectIds[2] = R.mipmap.icon_maintab_find_press;
        mIconUnselectIds[2] = R.mipmap.icon_maintab_find_normal;
//        Dvp_2_1_DynamicFragment dynamicFragment = Dvp_2_1_DynamicFragment.newInstance();
        DynamicFragment dynamicFragment = DynamicFragment.newInstance();
        mFragments.add(dynamicFragment);

        mTitles[3] = "我的";
        mIconSelectIds[3] = R.mipmap.icon_maintab_my_press;
        mIconUnselectIds[3] = R.mipmap.icon_maintab_my_normal;
        MineFragment mineFragment = MineFragment.newInstance();
        mFragments.add(mineFragment);

        commonBottomTab.setTextSelectColor(getResources().getColor(R.color.black));

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        commonBottomTab.setTabData(mTabEntities);

        commonBottomTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewpager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
//                if (position == 3)
//                {//生成tab上的小气泡
//                    commonBottomTab.showMsg(3, position++);
//                    UnreadMsgUtils.show(commonBottomTab.getMsgView(3), position++);
//                }
            }
        });

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                commonBottomTab.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        viewpager.setCurrentItem(0);
        viewpager.setOffscreenPageLimit(4);

    }

    @Override
    protected void initData() {
    }


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Constant.NUM_0:
                // 更新界面上的步数
//                kilometre.setText((msg.getData().getInt("step")*0.75)>=1000? msg.getData().getInt("step")*0.75 /1000+ "km": msg.getData().getInt("step")*0.75+"m");
                Logger.e("步数：" + msg.getData().getInt("step"));
                delayHandler.sendEmptyMessageDelayed(Constant.NUM_2, TIME_INTERVAL);
                break;
            case Constant.NUM_2:
                try {
                    Message msg1 = Message.obtain(null, Constant.NUM_0);
                    msg1.replyTo = mGetReplyMessenger;
                    messenger.send(msg1);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
        }
        return false;
    }


    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
        }
    }

    /**
     * 再按一次退出 逻辑
     */
    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast("再按一次返回键退出");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }
}
